import pathlib
import tkinter as tk
import tkinter.messagebox
from pathlib import Path
from tkinter import filedialog

from Common.CommonUtils import CommonUtils
from service.ExcelForm import ExcelForm
from service.WordWrite import WordWrite


class MessagePage(tk.Frame):
    """信息生成页面"""

    def __init__(self, master):
        super().__init__(master)
        self.master = master
        self.fiePath = ""
        # self.title("信息生成器")
        self.render()
        self.key = "暂停日志输出"
        # 添加一个定时器，每秒更新一次日志
        self.after(1000, self.update_log)

    def render(self):

        CommonUtils.set_information("开始渲染画面")
        # 文件选择按钮和文件路径显示标签
        self.choose_file_button = CommonUtils.styled_button(self, text="选择表格", command=self.open_file_dialog)
        self.choose_file_button.grid(row=0, column=0, padx=10, pady=10, sticky='nsew')

        self.choose_file_button_entry = tk.Entry(self, width=40)
        self.choose_file_button_entry.grid(row=0, column=1, padx=10, pady=10, sticky='nsew')

        # 文件选择按钮和文件路径显示标签
        self.choose_template_button = CommonUtils.styled_button(self, text="选择预警书模板",
                                                                command=self.open_template_dialog)
        self.choose_template_button.grid(row=1, column=0, padx=10, pady=10, sticky='nsew')

        self.choose_template_button_entry = tk.Entry(self, width=40)
        self.choose_template_button_entry.grid(row=1, column=1, padx=10, pady=10, sticky='nsew')

        # 文件保存路径文本标签和输入框
        self.save_file_path_label = tk.Label(self, text="文件保存目录路径：")
        self.save_file_path_label.grid(row=2, column=0, padx=10, pady=10, sticky='nsew')

        self.save_file_path_entry = tk.Entry(self, width=40)
        self.save_file_path_entry.grid(row=2, column=1, padx=10, pady=10, sticky='nsew')

        # 班主任联系方式选择表格按钮和联系方式输入框
        self.choose_teacher_contact_button = CommonUtils.styled_button(self, text="班主任联系方式",
                                                                       command=self.open_file_coordinator)
        self.choose_teacher_contact_button.grid(row=3, column=0, padx=10, pady=10, sticky='nsew')

        self.teacher_contact_entry = tk.Entry(self, width=40)
        self.teacher_contact_entry.grid(row=3, column=1, padx=10, pady=10, sticky='nsew')

        # 辅导员联系方式文本标签和输入框
        self.advisor_contact_label = tk.Label(self, text="辅导员联系方式：")
        self.advisor_contact_label.grid(row=5, column=0, padx=10, pady=10, sticky='nsew')

        self.advisor_contact_entry = tk.Entry(self)
        self.advisor_contact_entry.grid(row=5, column=1, padx=10, pady=10, sticky='nsew')

        # 文件保存时间文本标签和输入框
        self.save_time_label = tk.Label(self, text="文件保存时间：")
        self.save_time_label.grid(row=6, column=0, padx=10, pady=10, sticky='nsew')

        self.save_time_entry = tk.Entry(self)
        self.save_time_entry.grid(row=6, column=1, padx=10, pady=10, sticky='nsew')
        # 当前日期
        self.save_time_entry.insert('end', CommonUtils.date())

        # 开始生成按钮
        self.generate_button = CommonUtils.styled_button(self, text="开始生成", command=self.generate_info, width=20)
        self.generate_button.grid(row=7, column=0, padx=10, pady=10, sticky='nsew')

        # 日志生成按钮
        self.log_button = CommonUtils.styled_button(self, text="暂停日志输出", command=self.LogOutput, width=20)
        self.log_button.grid(row=7, column=1, padx=10, pady=10, sticky='nsew')

        # 显示信息的文本框
        self.info_textbox = tk.Text(self, height=10, width=50, wrap='word')
        self.info_textbox.grid(row=0, column=2, rowspan=8, padx=10, pady=10, sticky='nsew')

        scrollbar = tk.Scrollbar(self, command=self.info_textbox.yview)
        scrollbar.grid(row=0, column=3, rowspan=8, sticky='ns')

        self.info_textbox['yscrollcommand'] = scrollbar.set

        # 设置Grid布局的列和行权重，使其可以自动调整大小
        self.columnconfigure(2, weight=1)
        self.rowconfigure(0, weight=1)
        self.rowconfigure(1, weight=1)
        self.rowconfigure(2, weight=1)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(4, weight=1)
        self.rowconfigure(5, weight=1)
        self.rowconfigure(6, weight=1)
        self.rowconfigure(7, weight=1)

        CommonUtils.set_information("渲染画面成功")

    def open_file_dialog(self):
        file_path = filedialog.askopenfilename()
        self.fiePath = file_path
        # 清空文本框内容 插入尾部
        self.choose_file_button_entry.delete(0, 'end')
        self.choose_file_button_entry.insert(0, file_path)

    def open_template_dialog(self):
        file_path = filedialog.askopenfilename()
        # 清空输入框内容 插入尾部
        self.choose_template_button_entry.delete(0, 'end')
        self.choose_template_button_entry.insert(0, file_path)

    def open_file_coordinator(self):
        file_path = filedialog.askopenfilename()
        self.teacher_contact_entry.delete(0, 'end')
        self.teacher_contact_entry.insert(0, file_path)

    def generate_info(self):
        print(self.fiePath)

        teacher_contact = self.teacher_contact_entry.get()
        counselorInformation = self.advisor_contact_entry.get()
        save_time = self.save_time_entry.get()
        template_file_path = self.choose_template_button_entry.get()
        CommonUtils.set_date(self.save_time_entry.get())

        # 下面要添加一个辅导员的信息为空的警告框
        if not counselorInformation or len(counselorInformation) < 11:
            tk.messagebox.showwarning("警告", "请填写正确的辅导员联系方式！")
            return
        # 下面要添加一个老师联系方式为空的警告框
        if not teacher_contact:
            tk.messagebox.showwarning("警告", "请填写班主任联系方式！")
            return
        # 下面要添加一个模板文件为空的警告框
        if not template_file_path:
            tk.messagebox.showwarning("警告", "请填写要处理表格地址！")
            return
        # 下面要添加一个辅导员为空的警告框
        if not save_time:
            tk.messagebox.showwarning("警告", "请选择预警书模板地址！")
            return
        excelForm = ExcelForm(self.fiePath)
        personList = excelForm.extract()

        word_write = WordWrite(template_file_path, counselorInformation, teacher_contact)
        word_write.write(personList)

        CommonUtils.set_information("全部写入成功")
        self.DisplayFile()

        CommonUtils.set_information(
            f"辅导员联系方式：{counselorInformation}\n" + f"文件保存时间：{save_time}\n" + "保存成功")

    def LogOutput(self):
        if self.key == "暂停日志输出":
            self.key = "启动日志输出"
            self.log_button.config(text="启动日志输出")
        else:
            self.key = "暂停日志输出"
            self.log_button.config(text="暂停日志输出")
            # 设置定时器，每秒更新一次日志
            self.update_log()

    def update_log(self):
        if self.key == "启动日志输出":
            return

        # 清空文本框内容 插入尾部
        self.info_textbox.delete('1.0', 'end')
        Information = CommonUtils.get_information()
        for log_content in Information:
            self.info_textbox.insert('end', log_content + "\n")
        self.info_textbox.see('end')

        self.after(1000, self.update_log)

    def DisplayFile(self):
        # 获取当前工作目录的上一级目录
        parent_directory = Path.cwd().parent
        folder_path = parent_directory / "file"
        save_path = pathlib.Path.home() / "Desktop" / 'file'
        self.save_file_path_entry.insert("end", str(save_path))
        # 检查文件夹是否存在
        if folder_path.is_dir():
            print("文件夹目录：", folder_path)
            self.save_file_path_entry.insert("end", str(folder_path))
        else:
            print("文件夹不存在")
